package com.gitee.jjnnzb.designpatterninspring.business.login.manager.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.gitee.jjnnzb.designpatterninspring.business.login.manager.TokenGenerateManager;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.time.Instant;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Jjn
 * @since 2023/8/9 21:19
 */
@Service
@RequiredArgsConstructor
public class TokenGenerateManagerImpl implements TokenGenerateManager {
    
    private final KeyPair keyPair;
    
    private static final String SYSTEM = "system";
    private static final String USER_NAME = "username";
    private static final String USER_ID = "userId";
    private static final String JOBS = "authorities";
    private static final String ORG_ID = "orgId";
    
    @Override
    public void generateToken(Map<String, Object> map) {
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
        String token = JWT.create()
                .withClaim(SYSTEM, (String) map.get("systemCode"))
                .withClaim(USER_NAME, (String) map.get("userName"))
                .withClaim(USER_ID, (String) map.get("userId"))
                .withClaim(ORG_ID, (String) map.get("orgId"))
                .withArrayClaim(JOBS, new String[]{"test-role1", "test-role2"})
                .withIssuedAt(new Date())
                .withExpiresAt(Instant.now().plus(1, TimeUnit.DAYS.toChronoUnit()))
                .sign(algorithm);
        map.put("token", token);
    }
}

